<?php

include_once('Logging.php');
class SFExpressClass
{
    const USERNAME_TEST = 'vita1220';                                   # 测试 用户名
    const SHOPID_TEST = '3243279847393';                                # 测试 店铺ID
    const DEVKEY_TEST = '1fbfe64e957adb545c6f7e71f8b60fc1';             # 测试 密钥
    const DEVID_TEST = '1539906692';                                    # 测试 用户ID

    const URL = 'http://commit-openic.sf-express.com/open/api/external/';        # 下单接口地址【正式环境】
    const URL_TEST = 'http://commit-openic.sf-express.com/open/api/external/';   # 下单接口地址【测试环境】
    private $isDebug = true;
    private $dev_id = '';
    private $dev_key = '';
    private $userName = '';
    public function __construct($isDebug,$dev_key,$dev_id,$userName)
    {
        $this->isDebug = $isDebug;
        $this->dev_key = $dev_key;
        $this->dev_id = $dev_id;
        $this->userName = $userName;
    }

    /**
     * 下单
     * @param $data 数组参数
     * 主 经纬度
     * @return string
     */
    public function send_parameter($order)
    {


        $dev_id = (($this->isDebug) ? self::DEVID_TEST : ($this->dev_id));
        $dev_key = (($this->isDebug) ? self::DEVKEY_TEST : ($this->dev_key));

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'createorder';
        $parameter = array();

        if($this->isDebug){
            $parameter['shop_type']=1;                                              # 1：顺丰店铺ID ；2：接入方店铺ID
            $parameter['shop_id'] = self::SHOPID_TEST;                              # 测试店铺ID
        }else{
            $parameter['shop_type']=2;                                              # 1：顺丰店铺ID ；2：接入方店铺ID
            $parameter['shop_id'] = $order['shop_no'];                              # 店铺ID
        }
        $time = time();
        $parameter['dev_id'] = $dev_id;                                             # 同城开发者ID
        $parameter['shop_order_id'] = $order['shop_express_no'];                      # 商家订单ID
        $parameter['order_source'] = $order['source'];                              # 1：美团；2：饿了么；3：百度；4：口碑；其他请直接填写中文字符串值 2019-11-20 定 根据h订单来源
        $parameter['pay_type'] = $order['actual_pay'] ? 1 : 0;                      # 付款方式  1：已付款 0：货到付款
        $parameter['order_time'] = time();                                          # 下单时间
        $parameter['return_flag'] = 7;                                              # 返回字段控制标志位  全部返回为填入7
        $parameter['expect_time'] = strtotime($order['shop_delivery_time']);        # 期望送达时间

        if($order['shop_delivery_time']){
           // $end = date('Y-m-d H:i:s',strtotime('+1 day',time()));                # 大于当前时间1天
            $end = date('Y-m-d',strtotime(time())).' 23:59:59';              # 大于今日的都为预约单
            if($order['shop_delivery_time'] > $end){
                $parameter['is_appoint'] = 1;                                       # 是否预约单 0：非预约单；1：预约单   20191212 确认 顺丰只传预计送达时间

            }else{
                $parameter['is_appoint'] = 0;
            }
        }

        $parameter['is_insured'] = 0;                                               # 是否保价 0：非保价；1：保价 2019-11-20 确认不保价
        $parameter['remark'] = $order['shop_express_remark'];                       # 非必填 订单备注  string
        $parameter['push_time'] = $time;                                            # 推单时间
        $parameter['version'] = 17;                                                 # 版本号

        # 订单详情 obj
        $sf_push_type = isset($order['sf_push_type']) ? $order['sf_push_type'] : 99;
        $order_detail=array();
        $order_detail['total_price'] = $order['actual_pay'] * 100;                  # 用户订单总金额
        $order_detail['product_type'] = $sf_push_type;                              # 物品类型 1快餐;2送药;3百货;4脏衣服收;5干净衣服派;6生鲜;7保单;8饮品;9现场勘查;10快递;12文件证照;13蛋糕;14鲜花;15电子数码;16服装鞋帽;17汽车配件;18珠宝;20披萨;21中餐;99其他 2019-11-20 暂定 99
        $order_detail['weight_gram'] = $order['actual_weight'] * 1000;              # 物品重量 (单位：克)
        $order_detail['product_num'] = count($order['products']);                   # 物品个数
        $order_detail['product_type_num'] = 1;                                      # 物品种类个数
        $order_detail['lbs_type'] = 2;                                              # 坐标类型  1：百度坐标，2：高德坐标



        # 物品详情 数组
        $product_detail=array();
        foreach ($order['products'] as $k => $v) {
            $temp=array();
            $temp['product_name'] = $v['product_name'];                              # 物品名称
            $temp['product_num'] = $v['qty'];                                        # 物品数量
            $product_detail[]=$temp;
        }
        $order_detail['product_detail']=$product_detail;                             # 物品详情 数组结构

        # 收货人信息
        $receive=array();
        $receive['user_name'] = $order['receiver'];                                  # 用户姓名
        $receive['user_phone'] = $order['receiver_tel'];                             # 用户电话
        $receive['user_address'] = $order['receiver_address'];                       # 用户地址


        if ($this->isDebug){  //測試用
            $receive['user_address'] = '北京市海淀区学清路826号';
            $receive['user_lng'] = '116.3522490000';                                 # 用户经度
            $receive['user_lat'] = '40.0087090000';                                  # 用户纬度
        }else {
            # 20200426 判断是否有修改地址 有则用
            if($order['slat'] && $order['slng']){
                $receive['user_lng'] = $order['slng'];
                $receive['user_lat'] = $order['slat'];
            }else{
                $receive['user_lng'] = $order['lng'];
                $receive['user_lat'] = $order['lat'];
            }
        }

        # 固定参数
        $parameter['order_detail']=$order_detail;
        $parameter['receive']=$receive;

        $post_data = json_encode($parameter,JSON_UNESCAPED_UNICODE);
        $signChar = $post_data . "&{$dev_id}&{$dev_key}";
        $sign = base64_encode(MD5($signChar));

        $url .='?sign=' . $sign . '';
        $info = $this->http_post($url, $post_data, '', 'json', '');

        if (!empty($info)){
            $info=json_decode($info, true);
        }


        return $info;
    }


    /**
     * 查询订单 需要传 shop_id
     * @param $post 数组参数
     * @return string
     */
    function query($post)
    {
        $shop_id = (($this->isDebug) ? self::SHOPID_TEST : self::SHOPID);

        $dev_id = (($this->isDebug) ? self::DEVID_TEST : ($this->dev_id));
        $dev_key = (($this->isDebug) ? self::DEVKEY_TEST : ($this->dev_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'listorderfeed';
        $post['dev_id'] = $dev_id;
        $post['shop_id'] = $shop_id;
        $post_data = json_encode($post, JSON_UNESCAPED_UNICODE);
        $signChar = $post_data . "&{$dev_id}&{$dev_key}";
        $sign = base64_encode(MD5($signChar));
        $url .= '?sign=' . $sign . '';
        $info = $this->http_post($url, $post_data, '', '', '');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }


    /**
     * 取消订单
     * @param $post 数组参数
     * @return string
     */
    function cancel($express_order_id,$shop_id)
    {
        $dev_id = (($this->isDebug) ? self::DEVID_TEST : ($this->dev_id));
        $dev_key = (($this->isDebug) ? self::DEVKEY_TEST : ($this->dev_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'cancelorder';
        $post['order_id'] = $express_order_id;
        $post['order_type'] = 2;  //1、顺丰订单号 2、商家订单号
        $post['push_time'] = time();
        $post['dev_id'] = $dev_id;
        $post['shop_id'] = $shop_id;
        $post['shop_type'] = 2;

        $post_data = json_encode($post, JSON_UNESCAPED_UNICODE);
        $signChar = $post_data . "&{$dev_id}&{$dev_key}";
        $sign = base64_encode(MD5($signChar));
        $url .= '?sign=' . $sign . '';
        $info = $this->http_post($url, $post_data, '', '', '');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 获取配送员实时坐标 需要传shopid  功能暂未做调用
     * @param $post 数组参数
     * @return string
     */
    function riderlatestposition($express_order_no)
    {
        $dev_id = (($this->isDebug) ? self::DEVID_TEST : ($this->dev_id));
        $dev_key = (($this->isDebug) ? self::DEVKEY_TEST : ($this->dev_key));
//        $shop_id = (($this->isDebug) ? self::SHOPID_TEST : $shop_id);
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'riderlatestposition';
        $parameter['dev_id'] = $dev_id;
        $parameter['push_time'] = time();
        $parameter['order_id'] = $express_order_no;
        $parameter['order_type'] = 1;            # 查询订单ID类型：1、顺丰订单号 2、商家订单号

        $post_data = json_encode($parameter, JSON_UNESCAPED_UNICODE);
        $signChar = $post_data . "&{$dev_id}&{$dev_key}";
        $sign = base64_encode(MD5($signChar));
        $url .='?sign=' . $sign . '';
        $info = $this->http_post($url, $post_data, '', '', '');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 配送人轨迹H5 需要传shopid  功能暂未做调用
     * @param $post 数组参数
     * @return string
     */
    function riderh5view($post,$shop_id)
    {
        $dev_id = (($this->isDebug) ? self::DEVID_TEST : ($this->dev_id));
        $dev_key = (($this->isDebug) ? self::DEVKEY_TEST : ($this->dev_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'riderh5view';
        $post['dev_id'] = $dev_id;
        $post['shop_id'] = $shop_id;
        $post_data = json_encode($post, JSON_UNESCAPED_UNICODE);
        $signChar = $post_data . "&{$dev_id}&{$dev_key}";
        $sign = base64_encode(MD5($signChar));
        $url .= '?sign=' . $sign . '';
        $info = $this->http_post($url, $post_data, '', '', '');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }


    /**
     * 订单回调详情 需要传shopid 功能暂未做调用
     * @param $post 数组参数
     * @return string
     */
    function getcallbackinfo($post,$shop_id)
    {
        $dev_id = (($this->isDebug) ? self::DEVID_TEST : ($this->dev_id));
        $dev_key = (($this->isDebug) ? self::DEVKEY_TEST : ($this->dev_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'getcallbackinfo';
        $post['dev_id'] = $dev_id;
        $post['shop_id'] = $shop_id;
        $post_data = json_encode($post, JSON_UNESCAPED_UNICODE);
        $signChar = $post_data . "&{$dev_id}&{$dev_key}";
        $sign = base64_encode(MD5($signChar));
        $url .=  '?sign=' . $sign . '';
        $info = $this->http_post($url, $post_data, '', '', '');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }


    /**
     * 追加小费
     * 1 = 必传
     * 2 = 非必传
     * @param $order_id   ① 订单ID
     * @param $order_type    ① 订单ID类型   	1、顺丰订单号 2、商家订单号
     * @param $shop_id   ① 店铺ID
     * @param $shop_type     	 ① 店铺ID类型   	1：顺丰店铺ID 2：接入方店铺ID
     * @param $gratuity_fee  ① 订单小费，单位分，加小费最低不能少于100分
     * @param $serial_number     ② 加小费传入的唯一标识，用来幂等处理
     * @param $push_time     ① 取消时间；秒级时间戳
     * @return mixed|string
     */
    function AddOrderGratuityFee($order_id ,$shop_id ,$gratuity_fee)
    {
        $dev_id = (($this->isDebug) ? self::DEVID_TEST : ($this->dev_id));
        $dev_key = (($this->isDebug) ? self::DEVKEY_TEST : ($this->dev_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'addordergratuityfee';
        $post['dev_id'] = $dev_id;
        $post['shop_id'] = $shop_id;
        $post['order_id'] = $order_id;
        $post['order_type'] = 2;
        $post['shop_type'] = 2;
        $post['gratuity_fee'] = (int)$gratuity_fee*100;
        $post['serial_number'] = '';
        $post['push_time'] = time();
        $post_data = json_encode($post, JSON_UNESCAPED_UNICODE);
        $signChar = $post_data . "&{$dev_id}&{$dev_key}";
        $sign = base64_encode(MD5($signChar));
        $url .= '?sign=' . $sign . '';
        $info = $this->http_post($url, $post_data, '', '', '');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }


    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $post_file = false, $contenttype = '', $msg = '')
    {
        $log = new Logging();
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (empty($contenttype)) {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded; charset=utf-8'));
        } else if ($contenttype == "json") {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));

        }

        $strPOST = '';
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aGET = array();
            foreach ($param as $key => $val) {
                $aGET[] = $key . "=" . ($val);
            }
            $strPOST = join("&", $aGET);
        }

//        //$strPOST=http_build_query($param, '', '&');
//
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

        $time = strtotime(date('Y-m-d H:i:s'));
        $log->lfile('sf_express');
        $log->lwrite($time . ',' . ($url));
        $log->lwrite($time . ',' . json_encode(json_decode($param, true), JSON_UNESCAPED_UNICODE));
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);

        $log->lwrite($time . ',' . json_encode(json_decode($sContent, true), JSON_UNESCAPED_UNICODE));

        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


}

?>